package com.yanzhang.servlet;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.yanzhang.pojo.Bill;
import com.yanzhang.pojo.Provider;
import com.yanzhang.pojo.User;
import com.yanzhang.service.bill.BillService;
import com.yanzhang.service.bill.BillServiceImpl;
import com.yanzhang.service.provider.ProviderService;
import com.yanzhang.service.provider.ProviderServiceImpl;
import com.yanzhang.util.Constants;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 账单增删改查
 * @author yanzhang
 */
public class BillServlet extends HttpServlet {

    private BillService billService;
    private ProviderService providerService;

    public BillServlet() {
        billService = new BillServiceImpl();
        providerService = new ProviderServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method) {
            case "query": {
                query(req, resp);
                break;
            }
            case "add": {
                addBill(req, resp);
                break;
            }case "view": {
                viewBill(req, resp, "/jsp/billview.jsp");
                break;
            }
            case "toModify": {
                viewBill(req, resp, "/jsp/billmodify.jsp");
                break;
            }
            case "modify": {
                modifyBill(req, resp);
                break;
            }
            case "deleteBill": {
                deleteBill(req, resp);
                break;
            }
            case "getProviderList": {
                getProviderList(req, resp);
                break;
            }
            default: {

                break;
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }


    /**
     * 条件查询
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String productName = req.getParameter("queryProductName");
        String queryProviderId = req.getParameter("queryProviderId");
        String queryIsPayment = req.getParameter("queryIsPayment");
        System.out.println("queryProductName：" + productName + ", queryProviderId：" + queryProviderId + ", queryIsPayment：" + queryIsPayment);
        int providerId = 0;
        int isPayment = 0;
        Bill bill = new Bill();
        bill.setProductName(productName);
        if (StringUtils.isNullOrEmpty(queryProviderId)) {
            bill.setProviderId(0);
        } else {
            providerId = Integer.parseInt(queryProviderId);
            bill.setProviderId(providerId);
        }
        if (StringUtils.isNullOrEmpty(queryIsPayment)) {
            bill.setIsPayment(0);
        } else {
            isPayment = Integer.parseInt(queryIsPayment);
            bill.setIsPayment(isPayment);
        }
        List<Provider> providerList = providerService.getProviderList("", "");
        List<Bill> billList = billService.getBillList(bill);
        req.setAttribute("queryProductName", productName);
        req.setAttribute("queryProviderId", providerId);
        req.setAttribute("queryIsPayment", isPayment);
        req.setAttribute("providerList", providerList);
        req.setAttribute("billList", billList);
        req.getRequestDispatcher("/jsp/billlist.jsp").forward(req, resp);
    }

    /**
     * 新增一个账单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void addBill(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        BigDecimal countDecimal = new BigDecimal(productCount).setScale(2, BigDecimal.ROUND_DOWN);
        BigDecimal priceDecimal = new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN);
        User sessionUser = (User) req.getSession().getAttribute(Constants.USER_SESSION);

        Bill bill = new Bill(billCode, productName, null, productUnit, countDecimal, priceDecimal);
        bill.setProviderId(Integer.parseInt(providerId));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setCreatedBy(sessionUser.getId());
        bill.setCreationDate(new Date());

        if (billService.addBill(bill)) {
            resp.sendRedirect(req.getContextPath() + "/bill?method=query");
        } else {
            req.getRequestDispatcher("/jsp/billadd.jsp").forward(req, resp);
        }
    }

    /**
     * 获取账单信息
     * @param req
     * @param resp
     * @param uri
     * @throws ServletException
     * @throws IOException
     */
    private void viewBill(HttpServletRequest req, HttpServletResponse resp, String uri) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("billid"));
        Bill bill = billService.getBillById(id);
        if (bill == null) {
            resp.sendRedirect(req.getContextPath() + "/bill?method=query");
        } else {
            req.setAttribute("bill", bill);
            req.getRequestDispatcher(uri).forward(req, resp);
        }
    }

    /**
     * 修改账单信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void modifyBill(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        BigDecimal countDecimal = new BigDecimal(productCount).setScale(2, BigDecimal.ROUND_DOWN);
        BigDecimal priceDecimal = new BigDecimal(totalPrice).setScale(2, BigDecimal.ROUND_DOWN);
        User sessionUser = (User) req.getSession().getAttribute(Constants.USER_SESSION);

        Bill bill = new Bill(null, productName, null, productUnit, countDecimal, priceDecimal);
        bill.setId(Integer.parseInt(id));
        bill.setProviderId(Integer.parseInt(providerId));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setModifyBy(sessionUser.getId());
        bill.setModifyDate(new Date());

        if (billService.modifyBill(bill)) {
            resp.sendRedirect(req.getContextPath() + "/bill?method=query");
        } else {
            req.getRequestDispatcher("/jsp/billmodify.jsp").forward(req, resp);
        }
    }

    /**
     * 删除一个账单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void deleteBill(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String billId = req.getParameter("billid");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        if (StringUtils.isNullOrEmpty(billId)) {
            writer.write(JSONArray.toJSONString("notExist"));
            writer.close();
        } else {
            try {
                int id = Integer.parseInt(billId);
                if (billService.deleteBillById(id)) {
                    writer.write(JSONArray.toJSONString(true));
                } else {
                    writer.write(JSONArray.toJSONString(false));
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
                writer.write(JSONArray.toJSONString("notExist"));
            } finally {
                writer.close();
            }
        }
    }

    /**
     * 获取供应商列表
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void getProviderList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Provider> providerList = providerService.getProviderList(null, null);
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(providerList));
        writer.flush();
        writer.close();
    }
}
